#include <my_header.h>
#define TIMES 20000000

typedef struct share_value_s
{
    int num;
    pthread_mutex_t mLock;
}share_value_t;

void * threadFunc(void * argc);

/* usage */
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc,1);

    struct timeval beginTime,endTime;
    gettimeofday(&beginTime,NULL);

    share_value_t share_value;
    share_value.num = 0;
    pthread_mutex_init(&share_value.mLock,NULL);

    pthread_t tid;
    int ret_create = pthread_create(&tid,NULL,threadFunc,&share_value);
    THREAD_ERROR_CHECK(ret_create,"pthread_create");

    for(int i = 0;i < TIMES;i++)
    {
        pthread_mutex_lock(&share_value.mLock);
        share_value.num ++;
        pthread_mutex_unlock(&share_value.mLock);
    }

    pthread_join(tid,NULL);

    gettimeofday(&endTime,NULL);
    printf("num = %d\n",share_value.num);

    long total_ns = (endTime.tv_sec - beginTime.tv_sec)*1000000000L+(endTime.tv_usec - beginTime.tv_usec);
    double avg_ns = (double)total_ns /(TIMES *2);
    printf("avr_time = %.2f ns\n",avg_ns);

    return 0;
}

void * threadFunc(void * argc)
{
    share_value_t *pshare_value = (share_value_t *)argc;
    for(int i = 0; i < TIMES; i++)
    {
        pthread_mutex_lock(&pshare_value->mLock);
        pshare_value->num++;
        pthread_mutex_unlock(&pshare_value->mLock);
    }
    pthread_exit(NULL);
}

